﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Media.PhoneExtensions;
using SAFPodcast.WP8.Common.Tools;
using SAFPodcast.WP8.DTO.Entities;

namespace SAFPodcast.WP8.DAL.FileSystem
{
    public static class FileSystemAccessObject
    {
        public static void WriteFile(Stream stream, SongMetadata songData, String fileName)
        {
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                CopyFileIntoIsoStore(stream, fileName, songData);
            }
        }

        private static async void CopyFileIntoIsoStore(Stream stream, String fileName, SongMetadata songData)
        {
            using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (var targetFile = isoStore.CreateFile(fileName))
            {
                int length = Convert.ToInt32(stream.Length);
                var data = new byte[length];
                await stream.ReadAsync(data, 0, length);
                targetFile.Write(data, 0, data.Length);
            }

            var library = new MediaLibrary();
            library.SaveSong(new Uri(fileName, UriKind.RelativeOrAbsolute),
                songData,
                SaveSongOperation.MoveToLibrary);
        }

        public static void EmptyReceptionDir()
        {
            using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var files = isoStore.GetFileNames("????????-????-????-????-????????????.mp3");
                foreach (var file in files)
                {
                    isoStore.DeleteFile(file);
                }
            }
        }
    }
}
